const app = getApp()
const strokesHelper = require('./StrokesHelper');
let mainThis = null;
let io = require('../partyUtils/socket.io-wxapp');
let md5 = require('../partyUtils/md5.js')
let socket = '';

let connectType=1;

// 获取this
function getMainThis(tp)
{
  mainThis = tp;
}

// 连接websocket
function linkSocket(type){
     connectType = type;
    console.log("linkSocket|linkSocket");
    //1、当连接上之后的登录操作
    socket=io('wss://wx.ndmooc.com');
    socket.on('connect', () => {
     console.log(app.globalData.userInfo)
     socket.emit('get-roomid',mainThis.data.joinRoomMd5);
    });
    
    var isChangeRoom = false;
    
    //3、当 join-room 后，会马上返回本课堂状态
    socket.on('stat-info',(msg)=>{
        console.log("stat-info:");
        console.log(msg);
        mainThis.setData({
            "redNum":msg.redNum,
            "visitNum":msg.visitNum,
            'chatTotal':msg.chatTotal,
            'chatTotal':msg.commentNum,
            'myetag':msg.unionid
          })  
          if(msg.padInfo) {
            mainThis.setData({
                'writerAvator':msg.padInfo.avatar,
                'writerNickname':msg.padInfo.nickname,
                'writerId':msg.padInfo.signature,
              })  
          }
        msg.commentList.forEach(function (oneV, i) {
            if(oneV.msg.msgType=='msg'){
                if(oneV.signature==mainThis.data.myetag){
                    oneV.isme=true
                }else{
                    oneV.isme=false
                }
                oneV.canAction=false
                if(oneV.msg.timestamp){
                    oneV.msg.timestamp=mainThis.toTime(oneV.msg.timestamp*1000)
                }           
                mainThis.setData({         
                    chatlist: mainThis.data.chatlist.concat(oneV),
                })
            }         
        });
    });
    
    //4、ott 上写的笔记流
    socket.on('write_stream',(msg)=>{
        console.log("got a write_stream:"+msg);
        msg = msg.replace('],]',']]');
        var oneS = JSON.parse(msg);
        mainThis.singleDraw(oneS)   
    });
    
    
    //4.1、ott 上的控制指令
    socket.on('write_ctrl',(msg)=>{
        console.log("got a write_ctrl:"+msg);
        var oneS = JSON.parse(msg);
        mainThis.singleDraw(oneS)   
    });

    //5、上线某个人
    socket.on('someone-online',(msg)=>{
        console.log("someone-online:");
        console.log(msg);
        if(!msg){
            return;
        }

        if(msg.role &&
           msg.role == "ND_PAD"    
        ){
            mainThis.data.myStreaming = [];
        }
    });
    
    //6、有人发表留言或者发了红心
    socket.on('someone-talking',(msg)=>{
        console.log("someone-talking:");
        console.log(msg);
        if(msg.msg.msgType=='msg'){  //发消息
            var chatitem=[]
            var chatobj=msg
            if(msg.signature==mainThis.data.myetag){
                chatobj.isme=true
            }else{
                chatobj.isme=false
            }
            chatobj.canAction=false
            chatobj.msg.timestamp=mainThis.toTime(chatobj.msg.timestamp*1000)
            chatitem.push(chatobj)
            mainThis.setData({         
                chatlist: chatitem.concat(mainThis.data.chatlist),
                chatTotal:parseInt(mainThis.data.chatTotal)+1
            })
        }else{  //点赞
            mainThis.setData({         
                redNum:parseInt(mainThis.data.redNum)+1
            })
        }
    });
        
    //7、翻页去下页
    socket.on('change_page',(msg)=>{
        console.log("change_page:");
        console.log(msg);
        joinRoom(msg)
    });
     
    //8、本地短线
    socket.on('disconnecting',(msg)=>{
        console.log("disconnecting:");
        console.log(msg);
    });

    socket.on('reconnect', attemptNumber => {
        console.log('reconnect'+attemptNumber);
    });
  
    socket.on('reconnect_failed', () => {
        console.log('reconnect failed');
     });
  
      socket.on('reconnect_attempt', () => {
          console.log('reconnect_attempt');
      });

    //8、本地短线
    socket.on('disconnect',(msg)=>{
        console.log("disconnect:");
        console.log(msg);
        
        setTimeout(function(){
            socket.open();
        },1000);        

    }); 
    //9、某一个用户下线了
    socket.on('someone-offline',(msg)=>{
        console.log("someone-offline:");
        console.log(msg);
    });
    //10、得到一个哈希
    socket.on('get-roomid',(msg)=>{
        console.log("get-roomid:");
        console.log(msg);
        var roomMsg=msg.split('_');
        
        if(mainThis.data.tianRoomId != msg){
            strokesHelper.prepareTianFileByTerm(roomMsg[1],roomMsg[2],roomMsg[3]); //年纪、学期、第几页
            mainThis.data.tianRoomId = msg;
        }
        
        joinRoom(msg)
    });    
    //11、活的微信令牌
    socket.on('get-wx-access-token',(msg)=>{
        console.log("get-wx-access-token:");
        console.log(msg);
    });
    //13、删除一个评论的回调
    socket.on('remove-talking',(msgs)=>{
        console.log("got a remove-talking:"+msgs);
        mainThis.data.chatlist.splice(mainThis.data.chatlist.findIndex(item => item.msg.id == msgs), 1)
        mainThis.setData({         
            chatTotal:mainThis.data.chatTotal-1,
            chatlist:mainThis.data.chatlist
        })    
    });
    
    //14、wx code 错误登出
    socket.on('logout',(msg)=>{
        console.log("logout:");
        console.log(msg);
        if(msg.hasOwnProperty('statusCode') && msg.statusCode != 200){
            console.log('http请求错误')
        }else{
            var msgs=JSON.parse(msg);
            if(msgs.errcode == 40163 ||msgs.errcode == 40029){  //code已失效或无效
                wx.login({
                    success: res => {
                      if (res.code) {
                        mainThis.setData({
                          code:res.code
                        })
                        // 查看是否授权
                        wx.getSetting({
                          success: function (res) {
                            if (res.authSetting['scope.userInfo']) {
                                mainThis.setData({
                                hasAuthorize:true
                              })
                              wx.getUserInfo({
                                success: res => {
                                  console.log(res)
                                  wx.setStorage({
                                    key: 'userInfo',
                                    data: res.userInfo,
                                  })
                                  app.globalData.userInfo = res.userInfo;
                                  mainThis.setData({
                                    avator:app.globalData.userInfo.avatarUrl
                                  })
                                  connectType = 1; 
                                }
                              })
                            }else{
                              that.setData({
                                hasAuthorize:false
                              })
                              connectType = 0;
                            }         
                          }
                        })
                      }
                    }
                   });
            }
        }
    });
    function joinRoom(msg){
        var etag =mainThis.data.code     
        var loginInfo = ''
        //连接后加入一个房间
        if(connectType==1){ //  授权用户加入
            loginInfo = msg+"\r\nND_WX\r\n"+app.globalData.userInfo.avatarUrl+"\r\n"+app.globalData.userInfo.nickName+"\r\n"+app.globalData.userInfo.gender+"\r\n"+etag+"\r\n";
        }else{  //游客加入
            etag=''
            loginInfo = msg+"\r\nND_WX_ANONYMOUS\r\n"+mainThis.data.avator+"\r\n游客\r\ngender\r\n"+etag+"\r\n";
        }
        mainThis.setData({         
            roomid: msg
        })
        //连接后加入一个房间
        socket.emit('join-room', loginInfo);
    }
}
// 发射爱心
function sendHeart(id){
    var timestamp = Date.parse(new Date());
    var heartMsg = {msgType:"heart",timestamp:timestamp,canvasId:id,msgBody:"发射爱心"};
    socket.emit('speaking', heartMsg);
}
// 发射消息
function sendChat(msg){
    var timestamp = Date.parse(new Date())/1000;
    var msgMsg = {msgType:"msg",timestamp:timestamp,canvasId:"",msgBody:msg};
    socket.emit('speaking', msgMsg);
}
// 删除消息
function delmsg(id){
    socket.emit('remove-talking', id);
}
module.exports = {
  linkSocket,
  getMainThis,
  sendHeart,
  sendChat,
  delmsg
};